<?php

namespace app\unify\validate;

use think\db\Query;
use think\Validate;

use app\unify\model\Config as ConfigModel;

class ConfigGroup extends Validate
{

    const UPDATE = 'Update';
    const UPDATE_FIELD = "UpdateField";
    const SAVE = 'Save';
    const DELETE = "Delete";
    const UPDATE_SERIAL = "UpdateSerial";

    protected $rule = [
        'name|标识' => 'require|alpha|checkValidRecord',
        'title|标题' => 'require|checkValidRecord',
        'serial|排序号' => 'require|number',
        'id|编号' => 'require|integer',
        'ids|编号集合' => 'require|array',
        'field|字段' => 'require|in:serial',
        'value|值' => 'require',
    ];

    protected $scene = [
        self::SAVE => ['name', 'title', 'serial'],
        self::UPDATE => ['id', 'name', 'title', 'serial'],
        self::UPDATE_FIELD => ['ids', 'field', 'value'],
        self::UPDATE_SERIAL => ['id', 'serial'],
        self::DELETE => ['ids']
    ];

    public function checkValidRecord($value, $rule, $data = [])
    {
        $group = ConfigModel::where(function (Query $q) use ($data) {
            $q->whereOr("name", '=', $data['name'])
                ->whereOr("title", '=', $data['title']);
        })->find();
        if ($group) {
            if (empty($data['id'])) {
                return '标识和标题必需是唯一';
            }
            if ($group['id'] != $data['id']) {
                return '标识和标题必需是唯一';
            }
        }

        return true;
    }


}